<template>
  <div class="wrapper">
    <el-card>
      <div class="rowDiv">
        <div class="row-left">
          <div class="row-item margin-right">
            供应商名称：
            <el-select
              v-model="state.supplier_name"
              clearable
              placeholder="请选择状态"
              @change="changeSupplierName"
            >
              <el-option
                v-for="(item, index) in state.supper_arr"
                :key="index"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </div>
          <div class="row-item">
            供应商状态：
            <el-select
              v-model="state.s_type"
              clearable
              placeholder="请选择供应商状态"
              @change="changeSupplierType"
            >
              <el-option label="正常" value="10"></el-option>
              <el-option label="禁用" value="1"></el-option>
            </el-select>
          </div>
        </div>
        <div class="row-right">
          <searchDiv
            :placeholder="state.placeholder"
            @searchClick="searchClick"
            class="search-div"
          ></searchDiv>
          <el-button size="small" type="primary" @click="resetFields()"
            >重置
          </el-button>
          <el-button size="small" type="primary" @click="new_set_ware"
            >创建供应商
          </el-button>
        </div>
      </div>
      <el-table :data="state.tableData" style="width: 100%; margin-top: 20px">
        <el-table-column prop="id" label="供应商ID"></el-table-column>
        <el-table-column prop="name" label="供应商名称"></el-table-column>
        <el-table-column prop="liaison" label="联系人"></el-table-column>
        <el-table-column prop="phone" label="联系电话"></el-table-column>
        <el-table-column prop="address" label="地区"></el-table-column>
        <el-table-column prop="zip" label="关联门店"></el-table-column>
        <el-table-column prop="zip" label="商品数">
          <template #default="scope">
            <el-button type="text" @click="open_pro(scope.row)"
              >商品数</el-button
            >
          </template>
        </el-table-column>
        <el-table-column prop="pay_off" label="已履约货款"></el-table-column>
        <el-table-column prop="no_pay" label="待履约货款"></el-table-column>
        <el-table-column prop="note" label="备注"></el-table-column>
        <el-table-column prop="status" label="供应商状态"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              @click.native.prevent="editRow(scope.row)"
              type="text"
              size="small"
            >
              编辑
            </el-button>
            <el-button
              @click.native.prevent="deleteRow(scope.row)"
              type="text"
              size="small"
              :class="scope.row.status_code == 10 ? 'color-red' : 'color-green'"
            >
              {{ scope.row.status_code == 10 ? "禁用" : "启用" }}
              <!--删除-->
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--页码-->
      <el-row type="flex" class="row-bg" justify="end">
        <el-col :span="12">
          <Page
            v-if="state.totalPage"
            :totalPage="state.totalPage"
            @changePage="changePage"
          ></Page>
        </el-col>
      </el-row>
      <!-- 创建供应商 -->
      <el-dialog :title="state.title" v-model="state.new_dialogVisible" center>
        <span>
          <el-form
            :model="state.set_form"
            :rules="state.rules"
            ref="form"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="供应商名称" prop="supplier_name">
              <el-input
                v-model="state.set_form.supplier_name"
                placeholder="请输入供应商名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="联系人" prop="contact_name">
              <el-input
                v-model="state.set_form.contact_name"
                placeholder="请输入联系人"
              ></el-input>
            </el-form-item>
            <el-form-item label="联系电话" prop="contact_phone">
              <el-input
                v-model="state.set_form.contact_phone"
                placeholder="请输入联系电话"
              ></el-input>
            </el-form-item>

            <el-form-item label="所在地区">
              <el-col :span="6">
                <el-select
                  type="date"
                  placeholder="请选择"
                  @change="get_address_list(0, 1, 'change')"
                  v-model="state.set_form.province"
                  style="width: 100%"
                >
                  <template v-for="child in state.provinceArr" :key="child.id">
                    <el-option
                      :value="child.id"
                      :label="child.name"
                    ></el-option>
                  </template>
                </el-select>
              </el-col>
              <el-col :span="6">
                <el-select
                  placeholder="请选择"
                  @change="
                    get_address_list(state.set_form.province, 2, 'change')
                  "
                  v-model="state.set_form.city"
                  style="width: 100%"
                >
                  <template v-for="child in state.cityArr" :key="child.id">
                    <el-option
                      :value="child.id"
                      :label="child.name"
                    ></el-option>
                  </template>
                </el-select>
              </el-col>
              <el-col :span="6">
                <el-select
                  v-model="state.set_form.area"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <template v-for="child in state.areaArr" :key="child.id">
                    <el-option
                      :value="child.id"
                      :label="child.name"
                    ></el-option>
                  </template>
                </el-select>
              </el-col>
            </el-form-item>
            <el-form-item label="详细地址" prop="address">
              <el-input
                v-model="state.set_form.address"
                placeholder="请输入详细地址"
              ></el-input>
            </el-form-item>
            <el-form-item label="备注">
              <el-input
                type="textarea"
                v-model="state.set_form.note"
                placeholder="请输入备注"
              ></el-input>
            </el-form-item>
          </el-form>
        </span>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="close()">取 消</el-button>
            <el-button type="primary" @click="create_ware()">确 定</el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 商品信息 -->
      <el-dialog title="商品信息" v-model="state.pro_dialogVisible" center>
        <span>
          <el-table
            :data="state.goodsList"
            style="width: 100%; margin-top: 20px"
          >
            <el-table-column prop="name" label="商品名称"> </el-table-column>
            <el-table-column prop="stock" label="剩余库存"> </el-table-column>
            <el-table-column prop="price" label="平均进货价格">
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button
                  @click.native.prevent="deleteRow(scope.row)"
                  type="text"
                  size="small"
                >
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </span>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="close_pro()">关 闭</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted, getCurrentInstance } from "vue";
import { useRouter } from "vue-router";
import { ElNotification } from "element-plus";
import searchDiv from "@/components/Search.vue";
import Page from "../../components/Pagination.vue";

export default {
    name:"supplier_manager",
  components: {
    searchDiv,
    Page,
  },
  props: {},
  setup() {
    let form = ref("null");
    const { ctx } = getCurrentInstance();
    const router = useRouter();
    let state = reactive({
      new_dialogVisible: false,
      pro_dialogVisible: false,
      supplier_name: "",
      supplier_status: 10,
      s_type: "",
      keyword: "",
      page: 1,
      tag: "",
      set_form: {
        supplier_name: "",
        contact_name: "",
        contact_phone: "",
        province: "",
        city: "",
        area: "",
        address: "",
        note: "",
      },
      rules: {
        supplier_name: [
          { required: true, message: "请输入供应商名称", trigger: "blur" },
        ],
        contact_name: [
          { required: true, message: "请输入联系人", trigger: "blur" },
        ],
        contact_phone: [
          { required: true, message: "请输入联系电话", trigger: "blur" },
        ],
        address: [
          { required: true, message: "请输入详细地址", trigger: "blur" },
        ],
        note: [{ required: true, message: "请输入备注", trigger: "blur" }],
      },
      tableData: [],
      supper_arr: [],
      totalPage: 0,
      placeholder: "请输入关键词",
      goodsList: [], //供应商的商品
      provinceArr: [], //省
      cityArr: [], //市
      areaArr: [], //区
      title: "创建供应商",
      supplier_id: 0, //0:创建
    });
    onMounted(() => {
      getOrderlist();
    });

    //页码
    function changePage() {
      console.log("页码操作");
    }

    // 获取页面数据
    function getOrderlist() {
      ctx.$http
        .post("/tanxiaji/supplier/list/", {
          s_type: state.s_type,
          keyword: state.keyword,
          page: state.page,
          tag: state.tag,
        })
        .then((res) => {
          if (res.errno == 0) {
            var list = res.data;
            state.tableData = list.supplier_list;
            state.supper_arr = list.supplier_list;
            state.totalPage = list.pages;
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }

    //选择供应商
    function changeSupplierName() {
      console.log(state.keyword);
      getOrderlist();
    }

    //请选择供应商状态
    function changeSupplierType() {
      console.log(state.s_type);
      getOrderlist();
    }

    // 搜索框
    function searchClick(e) {
      console.log(e);
      state.keyword = e;
      getOrderlist();
    }

    // 重置
    function resetFields() {
      state.s_type = "";
      state.page = 1;
      state.tag = "";
      state.keyword = "";
      console.log(state.keyword, "重置");
    }

    // 关闭弹窗--并清除表单信息
    function close() {
      form.value.resetFields();
      state.new_dialogVisible = false;
    }

    // 编辑
    function editRow(e) {
      state.title = "编辑供应商";
      var item = Object.assign({}, e);
      state.supplier_id = item.id;
      get_address_list(0, 1, "");
      state.set_form = {
        supplier_name: item.name,
        contact_name: item.liaison,
        contact_phone: item.phone,
        province: item.area_ids[0],
        city: item.area_ids[1],
        area: item.area_ids[2],
        address: item.address,
        note: item.note,
      };
      state.new_dialogVisible = true;
    }

    // 查看详情
    function detailRow(idx, data) {
      console.log(idx.row.date);
      router.push({ path: "/ware_detail", query: { id: idx.row.date } });
    }

    // 禁用
    function deleteRow(e) {
      var item = Object.assign({}, e);
      ctx.$http
        .post("/tanxiaji/supplier/operate/", {
          supplier_id: item.id,
        })
        .then((res) => {
          if (res.errno == 0) {
            ElNotification.success(res.errmsg);
            getOrderlist();
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }

    // 打开新建弹窗
    function new_set_ware() {
      state.set_form = {
        supplier_name: "",
        contact_name: "",
        contact_phone: "",
        province: "",
        city: "",
        area: "",
        address: "",
        note: "",
      };
      state.title = "创建供应商";
      state.supplier_id = 0;
      get_address_list(0, 1, "");
      state.new_dialogVisible = true;
    }

    // 点击提交
    function create_ware() {
      form.value.validate((valid) => {
        if (valid) {
          var data = {
            name: state.set_form.supplier_name,
            liaison: state.set_form.contact_name,
            phone: state.set_form.contact_phone,
            address: state.set_form.address,
            area_id: state.set_form.area,
            grade: state.s_type,
            note: state.set_form.note,
            tag: "测试4",
          };
          var url = "";
          if (state.supplier_id == 0) {
            //创建
            url = "/tanxiaji/supplier/create/";
          } else {
            data.supplier_id = state.supplier_id;
            url = "/tanxiaji/supplier/edit/";
          }
          console.log(data, url);
          ctx.$http
            .post(url, data)
            .then((res) => {
              if (res.errno == 0) {
                ElNotification.success(res.errmsg);
                getOrderlist();
                close();
              }
            })
            .catch((err) => {
              ElNotification.error(err);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }

    //供应商的商品数
    function open_pro(e) {
      var item = Object.assign({}, e);
      state.pro_dialogVisible = true;
      get_goods_count(item.id);
    }

    //获取供应商的商品
    function get_goods_count(e) {
      ctx.$http
        .post("/tanxiaji/supplier/goods/", {
          supplier_id: e,
        })
        .then((res) => {
          if (res.errno == 0) {
            state.goodsList = res.data;
            console.log(state.goodsList);
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }

    // 关闭商品信息弹窗
    function close_pro() {
      state.pro_dialogVisible = false;
    }

    /**
     * 获取省市区
     * **/
    function get_address_list(id, type, change) {
      if (change == "change") {
        // 改变地址--change事件
        state.set_form.city = type == 2 ? state.set_form.city : "";
        state.set_form.area = "";
      }
      ctx.$http
        .get("/tanxiaji/addr/get_area/", { area_id: id })
        .then((res) => {
          if (res.errno == 0) {
            var list = res.data;
            if (type == 1) {
              //省
              state.provinceArr = list;
              var id =
                state.set_form.province != ""
                  ? state.set_form.province
                  : list[1].id;
              get_address_list(id, 2, "");
            } else if (type == 2) {
              //市
              state.cityArr = list;
              var id =
                state.set_form.city != "" ? state.set_form.city : list[0].id;
              get_address_list(id, 3, "");
            } else {
              //区
              state.areaArr = list;
            }
          }
        })
        .catch((err) => {
          err = "没有下一级，请求错误";
          ElNotification.error(err);
        });
    }

    // 创建仓库
    return {
      form,
      state,
      resetFields,
      editRow,
      detailRow,
      deleteRow,
      new_set_ware,
      open_pro,
      close_pro,
      create_ware,
      searchClick,
      getOrderlist,
      get_goods_count,
      changeSupplierName,
      changeSupplierType,
      changePage,
      close,
      get_address_list,
    };
  },
};
</script>
<style lang="scss" scoped>
.wrapper {
  height: 100%;
  .el-card {
    height: 100%;
    .rowDiv {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      .row-left {
        display: flex;
        justify-content: flex-start;
        .row-item {
          display: flex;
          align-items: center;
          white-space: nowrap;
        }
        .margin-right {
          margin-right: 30px;
        }
      }
      .row-right {
        display: flex;
        justify-content: flex-end;
        .search-div {
          margin-right: 10px;
        }
      }
    }
    .el-table /deep/ th {
      background-color: #eaeaea;
      text-align: center;
    }
    .el-table /deep/ td {
      text-align: center;
    }
    .el-select {
      width: 100%;
    }
  }
}

.row-bg {
  margin-top: 10px;
}

.el-col-6 {
  max-width: 33.3%;
  -webkit-box-flex: 0;
  flex: auto;
}

.color-red {
  color: red;
}

.color-green {
  color: #41ca21;
}
/deep/ .el-form-item__content {
  display: flex;
}
</style>